﻿<template>
  <div class="customer-container">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }"> 
      <el-form :model="queryParams" ref="queryForm" labelWidth="90">
          <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
                  <el-form-item label="关键字">
                      <el-input v-model="queryParams.searchKey" clearable="" placeholder="请输入模糊查询关键字" />
                  </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                  <el-form-item label="员工姓名">
                    <el-select v-model="queryParams.createUserId"  value-key="id" clearable placeholder="请输入员工姓名" collapse-tags collapse-tags-tooltip class="w100" filterable>
                      <el-option v-for="item in resData.userData" :key="item.id" :label="item.realName" :value="item.id" />
                    </el-select>
                  </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                  <el-form-item label="部门">
                      <el-cascader
                        :options="resData.orgTreeData"
                        :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name', expandTrigger: 'hover' }"
                        placeholder="所属机构"
                        clearable
                        class="w100"
                        v-model="queryParams.orgId"
                      >
                        <template #default="{ node, data }">
                          <span>{{ data.name }}</span>
                          <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                        </template>
                    </el-cascader>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
              </el-col>


              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="是否出报告">
                      <el-select v-model="queryParams.isReport" placeholder="是否出报告" clearable>
                        <el-option label="未出报告" :value="0" />
                        <el-option label="已出报告" :value="1" />
                      </el-select>
                  </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="是否收款">
                  <el-select v-model="queryParams.isCollected" placeholder="是否收款" clearable>
                        <el-option label="未收款" :value="0" />
                        <el-option label="已收款" :value="1" />
                      </el-select>
                  </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                  <el-form-item label="客户类型">
                      <el-select v-model="queryParams.type" placeholder="客户类型" clearable>
                        <el-option label="审计" :value="1" />
                        <el-option label="评估" :value="2" />
                      </el-select>
                  </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                  <el-form-item label="客户名称">
                      <el-input v-model="queryParams.cusName" clearable="" placeholder="请输入客户名称" />
                  </el-form-item>
              </el-col>
           
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
              </el-col>
         
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                  <el-form-item label="渠道对接">
                    <el-select v-model="queryParams.sourceChanne" value-key="id" clearable placeholder="渠道对接" collapse-tags collapse-tags-tooltip class="w100" filterable>
                      <el-option v-for="item in resData.sourceChanneList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                  <el-form-item label="渠道名称">
                     <el-input v-model="queryParams.sourceChanneName" clearable="" placeholder="请输入渠道名称" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                  <el-form-item label="收款日期">
                      <el-date-picker type="daterange" v-model="queryParams.collectedTimeRange" value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />

                  </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                  <el-form-item label="出报告日期">
                      <el-date-picker type="daterange" v-model="queryParams.reportTimeRange" value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />

                  </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
                  <el-form-item>
                      <el-button-group style="display: flex; align-items: center;">
                          <el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'customer:page'"> 查询 </el-button>
                          <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>
                          <el-button icon="ele-ZoomIn" @click="changeAdvanceQueryUI" v-if="!showAdvanceQueryUI" style="margin-left:5px;"> 高级查询 </el-button>
                          <el-button icon="ele-ZoomOut" @click="changeAdvanceQueryUI" v-if="showAdvanceQueryUI" style="margin-left:5px;"> 隐藏 </el-button>

                          <el-button type="primary" style="margin-left:50px;" icon="ele-Plus" @click="openAddCustomer" v-auth="'customer:add'"> 新增 </el-button>
                          <el-button icon="ele-FolderOpened" @click="openUploadDialog" v-auth="'customer:import'"> 导入 </el-button>
                          <el-button type="info" icon="ele-Delete" @click="batchCollectMoney1" v-auth="'customer:add'"> 批量收款 </el-button>
                          <el-button type="danger" icon="ele-Delete" @click="bacthDelete" v-auth="'customer:delete'"> 批量删除 </el-button>

                      </el-button-group>
                  </el-form-item>

              </el-col>
          </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table
				:data="tableData"
				style="width: 100%"
				v-loading="loading"
				tooltip-effect="light"
        row-key="id"
        :summary-method="getSummaries"
        show-summary
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
				border="">

        <el-table-column type="selection" width="45"></el-table-column>
        <el-table-column type="index" label="序号" width="45" align="center"/>
        <el-table-column prop="cusName" label="客户名称"  show-overflow-tooltip="" width="200" />
        <el-table-column prop="createUserName" label="员工姓名"  show-overflow-tooltip="" width="65" />
        <el-table-column prop="orgName" label="部门"  show-overflow-tooltip="" width="65" />
        <el-table-column prop="type" label="客户类型"  show-overflow-tooltip="" width="65">
          <template #default="scope">
								<el-tag type="warning" v-if="scope.row.type === 1"> 审计 </el-tag>
								<el-tag  v-else-if="scope.row.type === 2"> 评估 </el-tag>
								<el-tag v-else> 无 </el-tag>
							</template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量"  show-overflow-tooltip=""  width="50" />
        <el-table-column prop="money" label="点数"  show-overflow-tooltip=""  width="65" :sortable="true"/>
    
        <el-table-column prop="isReport" label="是否出报告"  show-overflow-tooltip="" width="82">
            <template #default="scope">
              <el-tag v-if="scope.row.isReport"> 已出报告</el-tag>
              <el-tag type="danger" v-else>未出报告</el-tag>
            </template>
        </el-table-column>

        <el-table-column prop="isCollected" label="是否收款"  show-overflow-tooltip="" width="80">
          <template #default="scope">
              <el-tag v-if="scope.row.isCollected"> 已收款 </el-tag>
              <el-tag type="danger" v-else> 未收款 </el-tag>
            </template>
          </el-table-column>
        <el-table-column prop="reportTime" label="出报告日期"  show-overflow-tooltip=""  :sortable="true">
          <template #default="scope">
             {{  FormatDateFun(scope.row.reportTime ) }}
          </template>
        </el-table-column>
        <el-table-column prop="collectedTime" label="收款日期"  show-overflow-tooltip="" :sortable="true" >
          <template #default="scope">
             {{  FormatDateFun(scope.row.collectedTime ) }}
          </template>
        </el-table-column>
        <el-table-column prop="propertyMoney" label="资产额(万)"  show-overflow-tooltip="" />

        <el-table-column prop="sourceChanne" label="渠道对接"  show-overflow-tooltip=""  :formatter="channeFormatter">
          <!-- <template #default="scope">
                  <el-tag v-for="item in resData.sourceChanneList" :key="item.id">
                    <span v-if="item.id === scope.row.sourceChanne">{{ item.name }}</span>
                  </el-tag>
							</template> -->
        </el-table-column>
        <el-table-column prop="sourceChanneName" label="渠道名称"  show-overflow-tooltip="" />
        <el-table-column prop="remark" label="备注"  show-overflow-tooltip="" />
        <el-table-column prop="voucherRemark" label="凭证备注"  show-overflow-tooltip="" />
        <el-table-column label="操作" width="200" align="center" fixed="right" show-overflow-tooltip="" v-if="auth('customer:detail') ||auth('customer:update') || auth('customer:delete')">
          <template #default="scope">
            <el-button icon="ele-View" size="small" text type="primary" @click="showInfo(scope.row)" v-auth="'customer:detail'"> 详情 </el-button>
            <el-button icon="ele-Edit" size="small" text="" type="primary" @click="openEditCustomer(scope.row)" v-auth="'customer:update'"> 编辑 </el-button>
            <el-button icon="ele-Delete" size="small" text="" type="primary" @click="delCustomer(scope.row)" v-auth="'customer:delete'"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
				v-model:currentPage="tableParams.page"
				v-model:page-size="tableParams.pageSize"
				:total="tableParams.total"
				:page-sizes="[10, 20, 50, 100, 200, 500]"
				size="small"
				background=""
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"
	/>
      <printDialog
        ref="printDialogRef"
        :title="printCustomerTitle"
        @reloadTable="handleQuery" />
      <editDialog
        ref="editDialogRef"
        :title="editCustomerTitle"
        @reloadTable="handleQuery"
      />
      <detailDialog ref="detailDialogRef" 
      :title="dialogTitle" 
      @reloadTable="handleQuery" />

    </el-card>


	 <el-dialog v-model="upload.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-UploadFilled /> </el-icon>
					<span> 客户导入 </span>
				</div>
			</template>
			<div>
				<el-upload 
            ref="uploadRef" 
            name="file"
            :auto-upload="false" 
            :limit="1" 
            :file-list="upload.fileList" 
            :on-change="handleChange"
            action= "" 
            accept=".xlsx,.xls"
            drag 
            >
            <el-icon class="el-icon--upload">
                <ele-UploadFilled />
              </el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip" style="margin-top: 15px;">
                  请上传大小不超过 10MB 的文件 &nbsp&nbsp&nbsp   
                  <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
                </div> 
              </template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="upload.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog> 
 
	
  </div>
</template> 

<script lang="ts" setup="" name="customer">
  import { ref ,reactive,onMounted} from "vue";
  import { ElMessageBox, ElMessage ,UploadInstance} from "element-plus";
  import { auth } from '/@/utils/authFunction';
  import { formatDate } from '/@/utils/formatTime';
  import {  useRouter } from 'vue-router';
  import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
  import editDialog from '/@/views/main/customer/component/editDialog.vue'
  import detailDialog from '/@/views/main/customer/component/detailDialog.vue';
  import { pageCustomer, deleteCustomer,downloadTemplate, importDataCus ,getUserList, batchDelete,batchCollectMoney  } from '/@/api/main/customer';
  import { getListCustomerChannel } from '/@/api/main/customerChannel';
  import { downloadByData, getFileName } from '/@/utils/download';
  import { request2 } from '/@/utils/request';
  import { SysOrg , SysUser} from '/@/api-services/models';
  import { SysUserApi, SysOrgApi } from '/@/api-services/api';
  import { getAPI } from '/@/utils/axios-utils';

  const showAdvanceQueryUI = ref(false);
  const printDialogRef = ref();
  const editDialogRef = ref();
  const detailDialogRef = ref();
  const loading = ref(false);
  const tableData = ref<any>([]);
  const router = useRouter();
  const queryParams = ref<any>({});
  const tableParams = ref({
    page: 1,
    pageSize: 20,
    field: 'createTime', // 默认的排序字段
    order: 'descending', // 排序方向
    descstr: 'descending', // 降序排序的关键字符
    total: 0 as any,
  });

interface Channel {
  id: number;
  name: string;
}
const resData = ref({
  totalMoney: 0,
  totalQuantity: 0,
  sourceChanneList: [] as Channel[],
  orgTreeData: [] as Array<SysOrg>,
  userData: [] as Array<SysUser>,
  selectlist : [] as EmptyObjectType[]
});

  const uploadRef = ref<UploadInstance>();
  const printCustomerTitle = ref("");
  const editCustomerTitle = ref("");
  const dialogTitle = ref("");

  const upload =   reactive({
    dialogUploadVisible: false,
    fileList: [] as any,
    isPublic: false,
    fileType: '',
  });


onMounted(async () => {
  handleQuery();
  loadOrgData();
  loadUserData();
});

// 查询机构数据
const loadOrgData = async () => {
  loading.value = true;
	let res = await getAPI(SysOrgApi).apiSysOrgListGet(0);
	resData.value.orgTreeData = res.data.result ?? [];
	loading.value = false;
};

const loadUserData = async () => {
  var res = await getUserList();
  resData.value.userData = res.data.result ?? [];
};


  // 打开上传页面
const openUploadDialog = () => {
  upload.fileList = [];
  upload.dialogUploadVisible = true;
};
// 通过onChanne方法获得文件列表
const handleChange = (file: any, fileList: []) => {
	upload.fileList = fileList;
};

const FormatDateFun = (date: any) => {
  if (date=="" || date =='' || date == undefined) return ""; 
  return formatDate(new Date(date), 'YYYY-mm-dd') 
};

// 上传
const uploadFile = async () => {
    if (upload.fileList.length < 1) return;

    const file = upload.fileList[0].raw;
    const formData = new FormData();
    formData.append('file', file);

    await importDataCus(formData)
    .then((res: any) => {
        handleQuery();
        ElMessage.success('上传成功');
        upload.dialogUploadVisible = false;
    	})
    	.catch((res: any) => {
    		alert(res);
    	});

    // request2({
    // 	url: '/api/customer/ImportDataCus',
    // 	method: 'post',
    // 	data: formData,
    // 	headers: {
    // 		'Content-Type': '',
    // 	},
    // })
    // 	.then((res: any) => {
    // 		ElMessage.success(res);

    //     debugger
    // 	})
    // 	.catch((res: any) => {
    // 		alert('上传错误');
    // 	});
};

/** 下载模板操作 */
const importTemplate = async () => {
    loading.value = true;
    var res = await downloadTemplate();
    var fileName = getFileName(res.headers);
    downloadByData(res.data as any, fileName);
    loading.value = false;
}

  // 改变高级查询的控件显示状态
  const changeAdvanceQueryUI = () => {
    showAdvanceQueryUI.value = !showAdvanceQueryUI.value;
  }

  // 查询操作
  const handleQuery = async () => {
    loading.value = true;
    var res = await pageCustomer(Object.assign(queryParams.value, tableParams.value));

    // tableData.value = res.data.result?.items ?? [];
    var resChannel = await getListCustomerChannel();
    resData.value.sourceChanneList = resChannel.data.result ?? [];

    tableData.value = res.data.result.pageData?.items ?? [];
    tableParams.value.total = res.data.result.pageData?.total;
    resData.value.totalMoney = res.data.result?.totalMoney ?? 0;
    resData.value.totalQuantity = res.data.result?.totalQuantity ?? 0;
    loading.value = false;
  };

//多选按钮改变事件
const handleSelectionChange = (val:EmptyObjectType[]) => {
	var selectProxy = JSON.parse(JSON.stringify(val));
	const emptyArray = [];
	for (let index = 0; index < selectProxy.length; index++) {
		emptyArray.push(selectProxy[index].id);
	}
	resData.value.selectlist =emptyArray; 
};


//批量删除
const bacthDelete = () => {
  if (resData.value.selectlist.length == 0) return false;
  ElMessageBox.confirm(`确定批量删除?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const ids = resData.value.selectlist.map((item) => {
        return item;
      });

      await batchDelete(ids).then(async () => {
        handleQuery();
        ElMessage.success('删除成功');
      });
    })
    .catch(() => { });
};


//批量收款
const batchCollectMoney1 = () => {
  if (resData.value.selectlist.length == 0) return false;
  ElMessageBox.confirm(`确定批量收款吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const ids = resData.value.selectlist.map((item) => {
        return item;
      });

      await batchCollectMoney(ids).then(async () => {
        handleQuery();
        ElMessage.success('收款成功');
      });
    })
    .catch(() => { });
};


 //列汇总
  const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums = [] as any;
  columns.forEach((column: any, index: any) => {
    if (index === 0) {
      sums[index] = '合计:';
      return;
    }
    else if (index === 6) {
      sums[index] = resData.value.totalQuantity;
      return;
    }
    else if (index === 7) {
      sums[index] = resData.value.totalMoney;
      return;
    }
  });
  return sums;
};


  // 列排序
  const sortChange = async (column: any) => {
    tableParams.value.field = column.prop;
    tableParams.value.order = column.order;
    await handleQuery();
  };

  // 打开新增页面
  const openAddCustomer = () => {
    editCustomerTitle.value = '添加客户档案表';
    editDialogRef.value.openDialog({ quantity: 1 });

  };

  // 打开打印页面
  const openPrintCustomer = async (row: any) => {
    printCustomerTitle.value = '打印客户档案表';
  }
  
  // 打开编辑页面
  const openEditCustomer = (row: any) => {
    editCustomerTitle.value = '编辑客户档案表';
    editDialogRef.value.openDialog(row);
  };

  //打开详情
  const showInfo = (row: any) => {
    dialogTitle.value = '查看客户详情';
    detailDialogRef.value.openDialog(row);
  };

  // 删除
  const delCustomer = (row: any) => {
    ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
  .then(async () => {
    await deleteCustomer(row);
    handleQuery();
    ElMessage.success("删除成功");
  })
  .catch(() => {});
  };

  // 改变页面容量
  const handleSizeChange = (val: number) => {
    tableParams.value.pageSize = val;
    handleQuery();
  };

  // 改变页码序号
  const handleCurrentChange = (val: number) => {
    tableParams.value.page = val;
    handleQuery();
  };

// 获取对接类型
const channeFormatter = (row: any, column: any, cellValue: any) => {
	 var resChanne =  resData.value.sourceChanneList.find((u: any) => u.id === cellValue)?.name;
   return resChanne;
};

</script>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>

